/**
 * 分类相关API
 * 对应后端CategoryRouter.js中的路由
 */
import api, { extractData } from './axios';
import { Category } from '../types';

/**
 * 获取类别列表
 * 对应后端GET /adminapi/categories路由
 */
export const getCategories = async () => {
  const response = await api.get('/categories');
  return extractData(response);
};

/**
 * 获取单个类别详情
 * 对应后端GET /adminapi/categories/:id路由
 */
export const getCategoryById = async (id: string | number) => {
  const response = await api.get(`/categories/${id}`);
  return extractData(response);
};

/**
 * 添加类别
 * 对应后端POST /adminapi/categories路由
 */
export const addCategory = async (data: Partial<Category>) => {
  const response = await api.post('/categories', data);
  return extractData(response);
};

/**
 * 更新类别
 * 对应后端PUT /adminapi/categories/:id路由
 */
export const updateCategory = async (id: number | string, data: Partial<Category>) => {
  // 确保data中不包含id和_id字段，避免MongoDB文档ID冲突
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const { id: _, _id: __, ...updateData } = data;
  
  const response = await api.put(`/categories/${id}`, updateData);
  return extractData(response);
};

/**
 * 删除类别
 * 对应后端DELETE /adminapi/categories/:id路由
 */
export const deleteCategory = async (id: number | string) => {
  const response = await api.delete(`/categories/${id}`);
  return response.data;
};

export default {
  getCategories,
  getCategoryById,
  addCategory,
  updateCategory,
  deleteCategory
}; 